package com.major.dawn.leetCode.list;

import sun.print.CUPSPrinter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ReverseList {

//    翻转链表
//    第一种方法   hashTable  讲链表转成数组，在循环构建链表
    public ListNode reverseList(ListNode head) {
        ArrayList<Integer> arrayList = new ArrayList<>();
        while (head != null) {
            arrayList.add(head.val);
            head = head.next;
        }

        int size = arrayList.size();
        if (size == 0) {
            return null;
        }

//        确定翻转后的首节点
        ListNode listNode = new ListNode(arrayList.get(size-1));

        ListNode cur = listNode;

        for (int i = size-2; i >= 0; i--) {
            ListNode next = new ListNode(arrayList.get(i));
            cur.next = next;
            cur = next;
        }
        return listNode;
    }

//    双指针，我隐约知道怎么实现   局部变量声明就会分配内存空间
    public ListNode reverseList2(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }

        ListNode cur = null;
        ListNode pre = head;
        ListNode next;

        while (pre != null) {

            next = pre.next;
            pre.next = cur;

            cur = pre;
            pre = next;

        }
        return cur;
    }

}
